<?php
namespace Utuo;

/**
 * 客户购物车
 * @author song
 */
class Cart {
	
	// 用户id
	private $uid;

	// 客户id
	private $cid;

	// 商品列表
	private $items = array(
// 			'商品id' => array(
// 					'productId(商品id)' => 1,
// 					'name(商品名称)' => '',
// 					'items(购买项)'  => array(
// 						'businessId(购物车中的记录id)' = array(
// 									'businessId(购物车中的记录id)' => 5,
// 									'productPrice(商品拍下价格)' => 8.90,
// 									'quantity(商品购买数量)' => 3,
// 									'pic(商品的图片)' => "http://...."
// 									'attrs(商品的属性)' => array(
// 										 "属性id" => "属性值id",
// 									     //... ...
// 									 ),
// 						   ),
// 						),
// 					),
// 			//... ...
	);
	
	private $config = array(
		'new_data' => true,
	);
	
	/**
	 * 获得购物车
	 * @param int $uid 登录的用户id
	 * @param int $sid 商户 id
	 * @return Ambigous <\Utuo\Cart, mixed, NULL>
	 */
	public final static function getCart($sid) {
		$sessionUser = session('user');
		$cart = session("cart");
		if($cart) {
			if(!$cart->getUid() and $sessionUser['id']) { // 登录后保存购物车
				$cart->setUid($sessionUser['id']);
				$cart->saveCart();
			}
			if($sid and $sid != $cart->getCid()) { // 商铺变更
				session("cart", null);
				$cart = null;
			}elseif( $sessionUser['id'] and $cart->getUid() and $sessionUser['id'] != $cart->getUid() ) { // 用户发生变更
				session("cart", null);
				$cart = null;
			}
		}
		if(!$cart) { // 无购物车
			$cart = new \Utuo\Cart($sessionUser['id'], $sid);
			session("cart", $cart);
		}
		return $cart;
	}

	// 商品数量
	public function getCount() {
		$count = 0;
		foreach ($this->items as $k => $v) {
			foreach ($v['items'] as $v1) {
				$count+=$v1['quantity'];
			}
		}
		return $count;
	}

	// 获得所有商品
	public function getItems() {
		if($this->config['new_data'] and $this->uid) {
			$this->items = array();
			$this->restoreCart();
		}
		return $this->items;
	}

	// 获得销售客户id
	public function getCid() {
		return $this->cid;
	}
	
	// 获得用户id
	public function getUid() {
		return $this->uid;
	}

	// 设置用户id
	public function setUid($uid) {
		$this->uid = $uid;
	}

	public function __construct($uid, $cid) {
		$this->setUid($uid);
		$this->cid = $cid;
		$this->_init();
	}

	// 初始化
	private function _init() {
		$this->saveCart();
	}

	// 持久化购物车
	public function saveCart() {
		if($this->uid) {
			$d = D("ProductCart");
			if($this->getCount() > 0) {
				// 删除数据库中原有购物车内容
				$d->where("cid=%d and uid=%d", $this->cid, $this->uid)->delete();
				// session商品同步入数据库
				foreach ($this->items as $item) { // 商品
					foreach ($item['items'] as $v0) { // 属性商品
						$d->add(array(
								'cid' => $this->cid,
								'owner_cid' => $item['ownerCid'], // 商品主
								'uid' => $this->uid,
								'business_id' => $v0['businessId'],
								'product_id' => $item['productId'],
								'product_name' => $item['name'],
								'product_attr' => arrayToString($v0['attrs']),
								'product_pic' => $v0['pic'],
								'product_count' => $v0['quantity'],
								'product_price' => $v0['productPrice'],
						));
					}
				}
			} else {
				$this->restoreCart();
			}
		}
	}
	

	/**
	 * 添加商品
	 * @param map $item 商品数据(除product_goods表数据外新增如下)
	 *    array(
	 *      selectedAttributes => array(),
	 *      productPrice => 0.00,
	 *      businessId => '',
	 *    )
	 * @param int $quantity 数据
	 */
	public function addItem($item, $quantity) {
		$fun = $this->uid ? "saveItem" : "addToSession";
		return $this->$fun($item, $quantity);
	}

	/**
	 * 从购物车中移除商品
	 * @param int $item_id 商品id
	 * @param string $businessId 业务id
	 */
	public function removeItem($item_id, $businessId) {
		if($this->uid) {
			if(false === M("ProductCart")->where(array(
					'cid'=>$this->cid,
					'uid' => $this->uid,
					'product_id' => $item_id,
					'business_id' => $businessId,))->delete()) {
					return false;
			}
		}
		// 更新session数据
		unset($this->items[$item_id]['items'][$businessId]);
		if(empty($this->items[$item_id]['items'])) {
			unset($this->items[$item_id]);
		}
		return true;
	}

	/**
	 * 更新商品
	 * @param int $item_id 商品id
	 * @param string $businessId 业务id
	 * @param map $updateItem 更新项   array('quantity'=>1)
	 */
	public function updateItem($item_id, $businessId, $updateItem) {
		if($this->uid) {
			$data = array();
			$config = array('quantity' => 'product_count'); // 可更新的字段配置
			foreach ($config as $k => $v) {
				key_exists($k, $updateItem) and $data[$v] = $updateItem[$k];
			}
			if(empty($data)) return false;
			if(false === M("ProductCart")->where(array(
					'cid'=>$this->cid,
					'uid' => $this->uid,
					'product_id' => $item_id,
					'business_id' => $businessId,))->save($data)){
					return false;
			}
		}
		// 更新session数据
		foreach ($updateItem as $k => $v) {
			$this->items[$item_id]['items'][$businessId][$k] = $v;
		}
		return true;
	}
	
	public function clearAll() {
		if($this->uid){
			D("ProductCart")->where("cid=%d and uid=%d", $this->cid, $this->uid)->delete();
		}
		$this->items = array();
	}

	/**
	 * 获得业务id
	 * @param unknown $item_id
	 * @return string
	 */
	public function getBusinessId($item_id) {
		return 'b'.session_id().$item_id.time().rand(0, 9).rand(0, 9);
	}

	/**
	 * 存入数据库
	 * @param map $item 商品数据
	 * @param int $quantity 数量
	 * @return boolean
	 */ 
	private function saveItem($item, $quantity) {
		$d = D("ProductCart");
		$selectedAttributesString = arrayToString($item['selectedAttributes']);
		$d->where(array(
				'cid' => $this->cid,
				'uid' => $this->uid,
				'product_id' => $item['id'],
				'product_attr' => $selectedAttributesString,
		));
		$d0 = clone $d;
		$result = false;
		if($productCartItem = $d->find()) {
			$result = $d0->setField("product_count", $productCartItem['product_count'] + $quantity);
		}else{
			$result = $d->add(array(
					'cid' => $this->cid,
					'owner_cid' => $item['ownerCid'],
					'uid' => $this->uid,
					'business_id' => $this->getBusinessId($item['id']),
					'product_id' => $item['id'],
					'product_name' => $item['name'],
					'product_attr' => $selectedAttributesString,
					'product_pic' => $item['pic'],
					'product_count' => $quantity,
					'product_price' => $item['productPrice']
			));
		}
		if($result === false) return false;
		$this->addToSession($item, $quantity);
		return true;
	}

	/**
	 * 存入session
	 * @param map $item 商品数据
	 * @param int $quantity  数量
	 * @return boolean
	 */
	private function addToSession($item, $quantity) {
		$cartItem = &$this->items[$item['id']];
		$selAttrs = $item["selectedAttributes"]; // 已选择的属性
		$businessId = $item['businessId'] ? $item['businessId'] : $this->getBusinessId($item['id']); // 业务编号
		$isExists = false; // 商品是否已存在
		// 查找相同商品
		if($cartItem) {
			foreach ($cartItem['items'] as &$v) {
				if($v['attrs'] == $selAttrs) {
					$v['quantity'] = $v['quantity'] + $quantity;
					$isExists = true;
					break;
				}
			}
		}else{
			// 新加商品
			$this->items[$item['id']] = array(
					'ownerCid' => $item['ownerCid'],
					'productId' => $item['id'],
					'name' => $item['name'],
			);
		}
		// 新加商品属性
		$isExists or $this->items[$item['id']]['items'][$businessId] = array(
				'businessId' => $businessId,
				'productPrice' => $item['productPrice'],
				'quantity' => $quantity,
				'attrs' => $selAttrs,
				'pic' => $item['pic'],
		);
		return true;
	}
	
	
	/**
	 * 还原数据库中的购物车
	 */
	private function restoreCart() {
		$d = D("ProductCart");
		$items = $d->where("cid=%d and uid=%d", $this->cid, $this->uid)->select();
		foreach ( $items as $v ) {
			$this->addToSession(array(
					'id' => $v['product_id'],
					'ownerCid' => $v['owner_cid'],
					'name' => $v['product_name'],
					'selectedAttributes' => toArray($v['product_attr']),
					'productPrice' => $v['product_price'],
					'pic' => $v['product_pic'],
					'businessId' => $v['business_id'],
			), $v['product_count']);
		}
	}

}